<template>
  <div class="register-container">
    <div class="bg-img">
      <el-image
        :src="require('@/assets/images/bg.jpg')"
        fit="cover"
        lazy
      ></el-image>
    </div>
    <div class="logo-container">
      <router-link :to="{ path: '/' }" class="text-white hover:text-white">
        首页
      </router-link>
      <el-divider direction="vertical"></el-divider>
      <span class="sub-title"> 瞪羚独角兽企业申报 </span>
    </div>
    <div class="form-container">
      <div class="form-box">
        <el-form
          ref="registerForm"
          :model="registerForm"
          :rules="registerFormRule"
          class="demo-registerForm"
        >
          <!-- <el-form-item label="" prop="userName">
            <el-input
              placeholder="手机号: 字母和数字组成(长度4-10)"
              v-model="registerForm.userName"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-user-solid"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item> -->

          <el-form-item label="" prop="userName">
            <el-input
              placeholder="账号"
              v-model="registerForm.userName"
              @blur.stop="verification(registerForm.userName)"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-user-solid"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item>

          <el-form-item label="" prop="password">
            <el-input
              minlength="5"
              maxlength="20"
              placeholder="请输入密码(长度5-20)"
              show-password
              v-model="registerForm.password"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-lock"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item>

          <el-form-item label="" prop="passwordSecond">
            <el-input
              minlength="5"
              maxlength="20"
              placeholder="请输入密码(长度5-20)"
              show-password
              v-model="registerForm.passwordSecond"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-lock"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item>

          <!-- <el-form-item label="" prop="phonenumber">
            <el-input
              type="number"
              placeholder="请输入手机号"
              v-model="registerForm.phonenumber"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-phone"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item> -->
          <el-form-item label="" prop="code" class="code-input">
            <el-input
              type="number"
              maxlength="5"
              placeholder="请输入验证码"
              v-model="registerForm.code"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-s-claim"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
            <div class="verify-btn-container">
              <el-button
                :disabled="isCanGetCode"
                type="primary"
                @click="getCode"
              >
                {{ isGetcode ? countDown : "" }}
                获取验证码
              </el-button>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              :loading="registerLoading"
              :disabled="isCanRegister"
              type="primary"
              @click="submitRegisterForm"
            >
              提交
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getForgetVerifyCode, updatePassword, getCodeImg, verification } from "@/api/login";
export default {
  name: "forgetPassword",
  computed: {
    isCanRegister() {
      let formName = "registerForm";
      let res = true;

      if (
        this.registerForm.password &&
        this.registerForm.userName &&
        this.registerForm.passwordSecond &&
        this.registerForm.code
      ) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            res = false;
          } else {
            res = true;
          }
        });
      }
      return res;
    },
    isCanGetCode() {
      return !(
        (
          this.registerForm.userName &&
          this.registerForm.password &&
          this.registerForm.passwordSecond &&
          !this.isGetcode &&
          !this.isUsedAccount
        )
        // this.registerForm.userName &&
        //
      );
    },
  },
  data() {
    var checkuserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户昵称不能为空"));
      }
      if (!/(?!^[a-z]+$)^[a-z][a-z0-9]{3,9}$/gi.test(value)) {
        callback(new Error("昵称必须是字母和数字组成"));
      } else {
        callback();
      }
    };
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      }
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("手机号码不合法"));
      } else {
        callback();
      }
    };

    var loginPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (value.length < 5 || value.length > 20) {
          callback(new Error("密码长度限制（5-20）"));
        }
        if (this.registerForm.passwordSecond !== "") {
          this.$refs.registerForm.validateField("passwordSecond");
        }
        callback();
      }
    };
    var checkCreditCode = (rule, value, callback) => {
      if (!value) {
        // return callback(new Error("统一社会信用代码不能为空"));
        return callback();
      }
      let reg = /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/;

      setTimeout(() => {
        if (!reg.test(value)) {
          callback(new Error("请输入有效统一社会信用代码"));
        } else {
          callback();
        }
      }, 1000);
    };
    var passwordSecond = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.registerForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      bgImg: "https://w.wallhaven.cc/full/pk/wallhaven-pkyqj3.jpg",
      isGetcode: false,
      // 该账号是或否已经在数据库内
      isUsedAccount: false,
      countDown: 60,
      registerFormRule: {
        userName: [
          { trigger: "blur", required: true, message: "请输入手机号" },
          { validator: checkPhone, trigger: "blur" },
        ],
        passwordSecond: [{ validator: passwordSecond, trigger: "blur" }],

        password: [{ validator: loginPass, trigger: "blur" }],
        code: [{ trigger: "blur", required: true, message: "请输入验证码" }],
      },
      registerLoading: false,
      registerForm: {
        userName: "",
        password: "",
        code: "",
        passwordSecond: "",
      },
    };
  },
  methods: {
    /**
     * 验证当前的手机号是否已存在
     * @param {String} userName 手机号
     */
    verification(value) {
      // 如果为空，则不验证
      if (!value) {
        return false;
      }

      /**
       * 接收两个参数
       * verificationType 验证类型0-注册 1-忘记密码
       * userName 验证的值
       */
      verification(1, value)
        .then((res) => {
          if (res.code == 200) {
            this.isUsedAccount = false;
          } else if (res.code == 500) {
            // 将该账号设为已经使用过的账号
            this.isUsedAccount = true;
            // this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.isUsedAccount = true;
          this.$message.error(err.split("Error: ")[1]);
        });
    },

    countDownFun() {
      if (this.countDown == 60) {
        let setTimeDo = null;
        let that = this;
        setTimeDo = setInterval(() => {
          that.countDown--;

          if (that.countDown == 0) {
            if (setTimeDo) {
              this.countDown = 60;
              clearInterval(setTimeDo);
              that.isGetcode = false;
            }
          }
        }, 1000);
      }
    },
    // 获取电话验证码
    getCode() {
      // 调用方法后 isGetcode  转为 true
      let phone = this.registerForm.userName;
      getForgetVerifyCode(phone).then((res) => {
        if (res.code == 200) {
          this.isGetcode = true;
          this.countDownFun();
          phone = null;
          if (res.msg) {
            this.$message({
              type: "success",
              message: res.msg,
            });
          }
        }
      });
    },

    submitRegisterForm() {
      let formName = "registerForm";
      this.registerForm.phonenumber = this.registerForm.userName;
      let that = this;
      this.$refs[formName].validate((valid) => {
        this.registerLoading = true;
        if (valid) {
          let data = that.registerForm;
          updatePassword(data).then((res) => {
            if (res.code == 200) {
              that.$message({
                type: "success",
                message: "注册成功,为您跳转至登录",
              });
              setTimeout(() => {
                this.registerLoading = false;
                that.$refs[formName].resetFields();
                that.$router.push({ path: "/login" });
              }, 1000);
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.register-container {
  position: relative;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  background-color: #efefef;

  .bg-img {
    position: absolute;
    z-index: 10;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    .el-image {
      width: 100%;
      height: 100%;
    }
  }

  .logo-container {
    position: absolute;
    top: 100px;
    z-index: 100;
    display: flex;
    align-items: center;
    height: 52px;
    width: 1200px;
    margin-bottom: 52px;
    font-size: 28px;

    .logo-img {
      height: 52px;
      width: 200px;

      .el-image {
        width: 100%;
        height: 100%;
      }
    }
    .sub-title {
      font-family: Source Han Sans CN, Source Han Sans CN-Medium;
      font-weight: 500;
      text-align: left;
      color: #ffffff;
    }
  }

  @keyframes form-animation {
    0% {
      transform: translateY(30px);
    }
    25% {
      transform: translateY(22px);
    }
    50% {
      transform: translateY(15px);
    }
    75% {
      transform: translateY(8px);
    }
    100% {
      transform: translateY(0px);
    }
  }
  @keyframes form-opacity {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  .form-container {
    z-index: 100;
    display: flex;
    justify-content: flex-end;
    width: 100%;
    height: 650px;
    border-radius: 10px;
    padding: 0 150px;
    // background-color: #fff;
    // box-shadow: 0 0 15px #979797;
    // transform: translateY(0px);
    // animation: form-animation 400ms ease;

    .form-box {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 500px;
      min-width: 500px;
      border-radius: 10px;
      margin-right: 0;
      opacity: 0;
      background-color: #fff;
      animation: form-opacity 800ms ease 200ms;
      animation-fill-mode: forwards;
      // border: 1px solid #f0f;
      .form-title {
        font-size: 20px;
        font-family: Source Han Sans CN, Source Han Sans CN-Medium;
        margin: 123px 0 66px 0;

        .active {
          font-size: 24px;
          font-weight: 500;
          text-align: left;
          color: #1678ff;
        }
      }

      .el-form {
        width: 366px;

        ::v-deep.el-input {
          input[type="number"] {
            -moz-appearance: textfield;
          }
          input[type="number"]::-webkit-inner-spin-button,
          input[type="number"]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
          }

          .el-input__inner {
            height: 48px;
            line-height: 48px;
            border-radius: 4px;
            padding-left: 50px;
          }
          .el-input__prefix {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 5px 10px;
          }
        }

        .code-input {
          ::v-deep .el-form-item__content {
            display: flex;

            justify-content: space-between;
            width: 100%;
          }
          ::v-deep .el-input {
            min-width: 60%;
            // width: 200px;
            // height: 48px;
            // line-height: 48px;
            // padding-right: 0;
            input[type="number"] {
              -moz-appearance: textfield;
            }
            input[type="number"]::-webkit-inner-spin-button,
            input[type="number"]::-webkit-outer-spin-button {
              -webkit-appearance: none;
              margin: 0;
            }
            .el-input__inner {
              border-radius: 4px 0 0 4px;
              // border-radius: 0;
              // border-width: 0 0 1px 0;
            }
          }

          .verify-btn-container {
            min-width: 40%;

            .el-button {
              border-radius: 0 4px 4px 0;
              // border-radius: 10px;
            }
          }
        }

        .el-button {
          height: 48px;
          width: 100%;
          font-size: 18px;
          border-radius: 4px;
        }
      }
    }
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
